import React, {useEffect, useState, useRef} from 'react';
import {Image, TouchableOpacity, StyleSheet, Animated} from 'react-native';

import icon_collection from '../assets/icon_collection.png';
import icon_collection_selected from '../assets/icon_collection_selected.png';

type Props = {
  value: boolean;
  onValueChanged?: (value: boolean) => void;
  size?: number;
};
export default (props: Props) => {
  // 声明一个showState变量，用来控制显示状态
  const [showState, setShowState] = useState<boolean>(false);
  // 解构赋值props中的value和onValueChanged，size默认为20
  const {value, onValueChanged, size = 20} = props;
  // 声明一个scale变量，用来控制缩放
  const scale = useRef<Animated.Value>(new Animated.Value(0)).current;
  // 声明一个alpha变量，用来控制透明度
  const alpha=  useRef<Animated.Value>(new Animated.Value(0)).current;
  // 当value改变时，设置showState的值
  useEffect(() => {
    setShowState(value);
  }, [value]);
  // 点击事件，改变showState的值，并改变透明度
  const onHeartPress = () => {
    const newState = !showState;
    setShowState(newState);
    onValueChanged?.(newState);
   if(newState){
      alpha.setValue(1); // 设置初始透明度为1
  const scaleAnim =    Animated.timing(scale,{
        toValue: 1.8,
        duration:300,
        useNativeDriver :false
      });
     const alphaAnim =    Animated.timing(alpha,{
        toValue: 0, 
        duration:400,
        delay:200,
        useNativeDriver :false
      });
      Animated.parallel([scaleAnim,alphaAnim]).start(); // 同时执行缩放和透明度动画
    } else {
      scale.setValue(0);
      alpha.setValue(0);
    }
  };
  // 返回组件
  return (
    <TouchableOpacity onPress={onHeartPress}>
      {/* 这里使用三元运算符来判断显示哪个图片 */}
      <Image
        style={styles.container}
        source={showState ? icon_collection_selected : icon_collection}></Image>
      <Animated.View
        style={{
          width: size,
          height: size,
          borderRadius: size / 2,
          borderWidth: size / 20,
          position: 'absolute',
          borderColor: '#e9a423',
          transform: [{scale: scale}],
          opacity: alpha,
        }}></Animated.View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    width: 20,
    height: 20,
    resizeMode: 'contain',
  },
});